<template>
  <a-card :bordered="true">
    <van-search placeholder="请选择条件查询" readonly @click="showSearchPopup" style="margin-top: -10px;width: 100%;padding: 0px;margin-bottom: 10px"/>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="addLabourDistribute" style="width: 100%" type="primary" icon="plus">新增</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="list">
        <van-list
          v-model="loading"
          :finished="finished"
          offset="100"
          finished-text="没有更多了"
          @load="onLoadList"
          :immediate-check="false"
        >
          <div
            class="customer-list"
            v-for="(item,i) in dataSource"
            :key="i"
            @click="labourDistributeDetail(item)"
          >
            <div>
              <div class="name">客户姓名：{{ item.customerName || '无' }}</div>
              <div class="contact">
                <span>劳务类型：{{ getDictValue('customer_labour_distribute_labour_type',item.labourType) }}</span>
                <span style="margin-left: 20px">劳务状态：{{ getDictValue('customer_labour_distribute_labour_status',item.labourStatus) }}</span>
              </div>
              <div class="contact">
                <span>项目地址：{{ item.projectAddress || '无' }}</span>
                <span style="margin-left: 20px">工期/天：{{ item.workDeadline || '无' }}</span>
                <span style="float: right;font-size: 20px;font-weight: bold">
                  <a @click.stop="changeShowMenu(item)"><a-icon type="more" /></a>
                </span>
              </div>
              <div class="contact">
                <span>项目名称：{{item.projectName || '无'}}</span>
              </div>
              <div class="contact">
                <span>劳务开始时间：{{item.labourBeginTime || '无'}}</span>
              </div>
              <div class="contact">
                <span>劳务结束时间：{{item.labourEndTime || '无'}}</span>
              </div>
              <div class="contact">
                <span>劳务金额：{{ item.labourMoney || '无' }}</span>
                <span style="margin-left: 20px;">下单状态：
                  <a-tag color="green" v-if="item.isBalanceAccounts == 0">已结算</a-tag>
                  <a-tag color="orange" v-else>未结算</a-tag>
                </span>
              </div>
            </div>
          </div>
        </van-list>
      </div>

      <!--<a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <span slot="action" slot-scope="text, record">
          <a @click="appointWorker(record)" v-if="[1,9].includes(record.labourStatus)">指派</a>
          <a-divider type="vertical" v-if="[1,9].includes(record.labourStatus)"/>

          <a @click="distribute(record)" v-if="[1,9].includes(record.labourStatus)">派发</a>
          <a-divider type="vertical" v-if="[1,9].includes(record.labourStatus)"/>

          <a @click="stopAppoint(record)" v-if="record.labourStatus === 3">停止派发</a>
          <a-divider type="vertical" v-if="record.labourStatus === 3"/>

          <a @click="editLabour(record)" v-if="[1,9,10].includes(record.labourStatus)">编辑</a>
          <a-divider type="vertical" v-if="[1,9,10].includes(record.labourStatus)"/>

          <a-popconfirm title="是否对该劳务进行确认?" @confirm="() => confirmLabour(record)">
            <a v-if="record.labourStatus === 5">确认劳务</a>
            <a-divider type="vertical" v-if="record.labourStatus === 5"/>
          </a-popconfirm>

          <a @click="rejectLabour(record)" v-if="record.labourStatus === 5">驳回</a>
          <a-divider type="vertical" v-if="record.labourStatus === 5"/>

          <a @click="rejectLabourDetail(record)" v-if="record.labourStatus === 8">驳回详情</a>
          <a-divider type="vertical" v-if="record.labourStatus === 8"/>

          <a @click="labourDistributeDetail(record)">劳务详情</a>
          <a-divider type="vertical" v-if="[1,9,10].includes(record.labourStatus)"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
            <a v-if="[1,9,10].includes(record.labourStatus)">删除</a>
          </a-popconfirm>
        </span>

      </a-table>-->
    </div>

    <van-popup v-model="showSearchPopupFlag" position="top" >
      <a-card :bordered="false">
        <a-form layout="inline" @keyup.enter.native="searchQuery">
          <div>项目名称：<a-input placeholder="请输入项目名称" v-model="queryParam.projectName"></a-input></div>
          <div style="margin-top: 5px">项目地址：<a-input placeholder="请输入项目地址" v-model="queryParam.projectAddress"></a-input></div>
          <div style="margin-top: 5px">备注：<a-input placeholder="请输入备注" v-model="queryParam.remarks"></a-input></div>
          <a-row :gutter="24" style="margin-bottom: 10px;margin-top: 10px">
            <a-col :span="12">
              <a-button type="primary" style="width: 100%" @click="searchQuery" icon="search">查询</a-button>
            </a-col>
            <a-col :span="12">
              <a-button type="primary" @click="searchReset" icon="reload" style="width: 100%">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </van-popup>

    <van-action-sheet
      v-model="showMenu"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="selectMenu"
    />

    <a-drawer
      title="驳回记录"
      placement="right"
      width="100%"
      :closable="true"
      :visible="visible"
      @close="onClose">
      <a-timeline style="margin-top: 10px">
        <a-timeline-item v-for="(item,index) in this.rejectLabourList" :key="index" >
          <a-card  :title="'驳回时间：'+item.createTime" style="width: 100%">
            <div>
              <span>驳回原因：{{item.rejectCause}}</span><br>
              <span v-if="item.rejectImage!=null && item.rejectImage!=''">
                驳回图片：<img style="width: 100px;height: 100px;margin-right: 10px" @click="imageDetail(img,item.rejectImageArr)" v-for="(img,imgIndex) in item.rejectImageArr" :key="imgIndex" :src="img">
              </span>
              <span v-if="item.rejectImage == null || item.rejectImage == ''">
                驳回图片：无
              </span>
            </div>
          </a-card>
        </a-timeline-item>
      </a-timeline>
    </a-drawer>

    <!--<a-modal :visible="previewVisible" :footer="null" @cancel="handleClose">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>-->
    <a-modal :visible="previewVisible" :footer="null" centered width="auto" @cancel="handleClose">
      <JReview :path="previewImage" :pathList="imgList"></JReview>
    </a-modal>

    <add-labour-modal ref="addLabourModal" @ok="modalFormOk"></add-labour-modal>
    <labour-detail-modal ref="LabourDetailModal"></labour-detail-modal>
    <appoint-worker-modal ref="appointWorkerModal" @selectFinished="selectOK"></appoint-worker-modal>
    <reject-labour-modal ref="rejectLabourModal" @ok="modalFormOk"></reject-labour-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { filterObj } from '@/utils/util';
  import { deleteAction, postAction,getAction,downFile,getFileAccessHttpUrl } from '@/api/manage'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import {filterDictTextByCache} from '@comp/dict/JDictSelectUtil'
  import addLabourModal from "./modules/addLabourModal";
  import LabourDetailModal from "./modules/labourDetailModal";
  import appointWorkerModal from "./modules/appointWorkerModal";
  import rejectLabourModal from "./modules/rejectLabourModal";

  export default {
    name: 'labourList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      appointWorkerModal,
      LabourDetailModal,
      addLabourModal,
      rejectLabourModal,
    },

    data () {
      return {
        currentCustomerId: 0,   //当前客户id
        currentId: 0,   //当前劳务id
        description: '客户劳务派发表管理页面',
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        imgList:[],
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'客户姓名',
            align:"center",
            dataIndex: 'customerName'
          },
          {
            title:'劳务类型',
            align:"center",
            dataIndex: 'labourType',
            customRender: (text) => {
              //字典值翻译通用方法
              return filterDictTextByCache('customer_labour_distribute_labour_type', text);
            }
          },
          {
            title:'劳务金额',
            align:"center",
            dataIndex: 'labourMoney'
          },
          {
            title:'项目名称',
            align:"center",
            dataIndex: 'projectName'
          },
          {
            title:'项目地址',
            align:"center",
            dataIndex: 'projectAddress'
          },
          {
            title:'劳务开始时间',
            align:"center",
            dataIndex: 'labourBeginTime'
          },
          {
            title:'劳务结束时间',
            align:"center",
            dataIndex: 'labourEndTime'
          },
          {
            title:'工期/天',
            align:"center",
            dataIndex: 'workDeadline'
          },
          {
            title:'是否结算',
            align:"center",
            dataIndex: 'isBalanceAccounts',
            customRender:function (text) {
              return text == 0 ? <a-tag color="green">已结算</a-tag> : <a-tag color="orange">未结算</a-tag>
            }
          },
          {
            title:'劳务状态',
            align:"center",
            dataIndex: 'labourStatus',
            customRender: (text) => {
              //字典值翻译通用方法
              return filterDictTextByCache('customer_labour_distribute_labour_status', text);
            }
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remarks',
            customCell:() => {
              return {
                style: {
                  wordWrap:'break-word',
                  wordBreak:'break-all',
                  whiteSpace:'normal',
                  minHeight:'50px',
                  width: '700px',
                }
              }
            }
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/ghCustomerLabourDistribute/allList",
          delete: "/ghCustomerLabourDistribute/delete",
          deleteBatch: "/ghCustomerLabourDistribute/deleteBatch",
          exportXlsUrl: "/ghCustomerLabourDistribute/exportXls",
          importExcelUrl: "/ghCustomerLabourDistribute/importExcel",
          edit: "/ghCustomerLabourDistribute/edit",
          rejectLabourList: "/ghCustomerLabourDistributeReject/list",
        },
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        dictOptions:{},
        superFieldList:[],
        visible: false,
        previewVisible: false,
        rejectLabourList:[],
        previewImage:"",
        finished: false,
        loading: false,
        showMenu: false,
        actions: [],
        currentLabour:{},
        showSearchPopupFlag: false,
      }
    },
    created() {
      this.loadData(1);
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      showSearchPopup(){
        this.showSearchPopupFlag = true
      },
      searchQuery(){
        this.loadData(1);
        this.selectedRowKeys = []
        this.selectedRows = []
        this.showSearchPopupFlag = false
      },
      searchReset() {
        this.queryParam = {}
        this.selectedRowKeys = []
        this.selectedRows = []
        this.showSearchPopupFlag = false
        this.loadData(1);
      },
      initDictConfig(){
      },
      //驳回
      rejectLabour(record){
        this.$refs.rejectLabourModal.labourId = record.id;
        this.$refs.rejectLabourModal.visible = true;
        this.$refs.rejectLabourModal.title = "驳回";
      },
      //驳回详情
      rejectLabourDetail(record){
        this.visible = true;
        this.getRejectLabourList(record.id);
      },
      //查询驳回列表
      getRejectLabourList(labourId) {
        getAction(this.url.rejectLabourList,{
          labourId: labourId,
        }).then((res)=>{
          if (res.success){
            this.rejectLabourList = res.result;
          }
        })
      },
      //确认劳务
      confirmLabour(record){
        let params = record;
        params.labourStatus = 6;
        postAction(this.url.edit, params).then((res) => {
          if (res.success) {
            this.$message.success("操作成功")
            this.loadData(1);
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      //派发
      distribute(record){
        postAction(this.url.edit, {
          id: record.id,
          labourStatus: 3
        }).then((res) => {
          if (res.success) {
            this.$message.success("已派发")
            this.loadData(1);
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      //停止派发
      stopAppoint(record){
        let params = {};
        params.id = record.id;
        params.labourStatus = 9;
        postAction(this.url.edit, params).then((res) => {
          if (res.success) {
            this.$message.success("操作成功")
            this.loadData(1);
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      //指派工人
      appointWorker(record){
        this.currentId = record.id;
        //this.$refs.AppointWorkerModal.onClearSelected();
        this.$refs.appointWorkerModal.visible = true
        this.$refs.appointWorkerModal.title = "指派工人";
      },
      selectOK(data) {
        let params = {};
        params.id = this.currentId;
        params.workerId = data.id;
        params.workName = data.workerName;
        params.workPhone = data.workerPhone;
        params.labourStatus = 5;
        postAction(this.url.edit, params).then((res) => {
          if (res.success) {
            this.$message.success("指派成功")
            this.loadData(1);
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      labourDistributeDetail(record){
        /*console.log(1111)
        if (!this.showMenu) return*/
        this.$refs.LabourDetailModal.model = record;
        this.$refs.LabourDetailModal.visible = true;
        this.$refs.LabourDetailModal.title = "劳务详情";
      },
      addLabourDistribute(){
        this.$refs.addLabourModal.add();
        this.$refs.addLabourModal.title = "添加劳务";
      },
      editLabour(record){
        this.$refs.addLabourModal.edit(record);
        this.$refs.addLabourModal.title = "编辑劳务";
      },
      modalFormOk(){
        this.loadData(1);
      },
      onLoadList(e){
        this.ipagination.current++
        this.loadData(this.ipagination.current)
      },
      loadData(arg) {
        if(!this.url.list){
          this.$message.error("请设置url.list属性!")
          return
        }
        //加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1;
          this.dataSource = []
          this.finished = false;
        }
        var params = this.getQueryParams();//查询条件
        //params.customerId = this.currentCustomerId;
        this.loading = true;
        getAction(this.url.list, params).then((res) => {
          if (res.success) {
            this.dataSource = [...this.dataSource, ...res.result.records]
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            } else {
              this.ipagination.total = 0;
            }
          } else {
            this.$message.warning(res.message)
          }
          if(res.result.records.length<10){
            this.finished = true;
          }
        }).finally(() => {
          this.loading = false
        })
      },
      getQueryParams() {
        //获取查询条件
        let sqp = {}
        if(this.superQueryParams){
          sqp['superQueryParams']=encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter ,this.filters);
        param.field = this.getQueryField();
        param.pageNo = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize;
        return filterObj(param);
      },
      getQueryField() {
        //TODO 字段权限控制
        var str = "id,";
        this.columns.forEach(function (value) {
          str += "," + value.dataIndex;
        });
        return str;
      },
      onClose() {
        this.visible = false;
      },
      //关闭预览照片
      handleClose() {
        this.previewVisible = false;
      },
      imageDetail(imgUrl,imgList){
        this.imgList = imgList;
        this.previewVisible = true;
        this.previewImage = imgUrl;
      },
      getDictValue(code,value){
        if (value != null){
          let dictValue = filterDictTextByCache(code,value);
          if (dictValue != null && dictValue != ""){
            return dictValue;
          }else {
            return "无"
          }
        }else {
          return "无"
        }
      },
      changeShowMenu(item){
        this.actions = [];
        if ([1,9].includes(item.labourStatus)){
          this.actions = [...this.actions, ...[{name: '指派',click: 'appointWorker'},{name: '派发',click: 'distribute'}]]
        }
        if ([3].includes(item.labourStatus)){
          this.actions = [...this.actions, ...[{name: '停止派发',click: 'stopAppoint'}]]
        }
        if ([5].includes(item.labourStatus)){
          this.actions = [...this.actions, ...[{name: '确认劳务',click: 'confirmLabour'},{name: '驳回',click: 'rejectLabour'}]]
        }
        if ([8].includes(item.labourStatus)){
          this.actions = [...this.actions, ...[{name: '驳回详情',click: 'rejectLabourDetail'}]]
        }
        if ([10].includes(item.labourStatus)){
          this.actions = [...this.actions, ...[{name: '编辑',click: 'editLabour'},{name: '删除',click: 'handleDelete'}]]
        }
        this.showMenu = true;
        this.currentLabour = item;
      },
      selectMenu(selectItem){
        this[selectItem.click](this.currentLabour);
      },
      handleDelete(item){
        if(!this.url.delete){
          this.$message.error("请设置url.delete属性!")
          return
        }
        let that = this;
        that.loading = true;
        this.$confirm({
          title: "确认删除",
          content: "是否删除数据?",
          onOk: function () {
            that.loading = true;
            deleteAction(that.url.delete, {id: item.id}).then((res) => {
              if (res.success) {
                //重新计算分页问题
                that.reCalculatePage(1)
                that.$message.success(res.message);
                that.loadData(1);
              } else {
                that.$message.warning(res.message);
              }
            }).finally(() => {
              this.loading = false
            });
          }
        });
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
  .van-popup /deep/ .van-overlay{
    background-color: rgba(0,0,0,0.05) !important;
  }
  .list{
    overflow-y: scroll;
    height:100vh;
  }
  ::-webkit-scrollbar {
    display: none;
  }
  .customer-list {
    align-items: center;
    border-top: 1px solid #d9d9d9;
    /*height: 120px;*/
  }
  .name{
    margin-top: 10px;
    margin-bottom: 5px;
    font-size: 13px;
    color: #161616;
    line-height: normal;
  }
  .contact{
    font-size: 12px;
    color: #a39f9f;
    margin-bottom: 5px;
  }
</style>